#include "../include/PageLRUCach.h"
#include  "../include/log4cppuse.h"
#include <iostream> 
PageLRUCache::PageLRUCache(int capacity)
: _capacity{ capacity }
{
    // 修正：在构造函数体内初始化 _cachesum
    int cacheCount = static_cast<int>(std::ceil(std::thread::hardware_concurrency() / 0.75));
    _cachesum.resize(cacheCount);
    
    for (int i = 0; i < cacheCount; ++i) {
        _cachesum[i].first = std::make_shared<list<CacheNode>>();
        _cachesum[i].second = std::make_shared<unordered_map<string, list<CacheNode>::iterator>>();
        _cachesum[i].second->reserve(_capacity);
    }
}


PageLRUCache::~PageLRUCache()
{
}
    // 获取缓存中的值
vector<tuple<int, double, vector<KeywordInfo>>> PageLRUCache::get(string key)
{
    std::lock_guard<std::mutex> lock(_mutex);
   
    std::hash<string> hash;
    int index = hash(key) % _cachesum.size();

    auto& cache = _cachesum[index].first;
    auto& index_map = _cachesum[index].second;
    auto iter = index_map->find(key);
    if (iter == index_map->end()) {
        return {};
    }
    auto entry_iter = iter->second;
    auto value = entry_iter->m_values;  
    cache->splice(cache->begin(), *cache, entry_iter);

    string logmsg="PageLRUCache 缓存命中 key: "+key;
    LOG_INFO(logmsg.c_str());
    return value;
}

    // 插入缓存
void PageLRUCache::put(string key, vector<tuple<int, double, vector<KeywordInfo>>> values)
{
    std::lock_guard<std::mutex> lock(_mutex);
    std::hash<string> hash;
    int index = hash(key) % _cachesum.size();

    auto& cache = _cachesum[index].first;
    auto& index_map = _cachesum[index].second;
    auto iter = index_map->find(key);
    if (iter != index_map->end()) {
        // 存在，更新值
        auto entry_iter = iter->second;
        entry_iter->m_values = values;  
        cache->splice(cache->begin(), *cache, entry_iter);
        return;
    }

    // 不存在
    cache->emplace_front(CacheNode{key, values});
    // 构建节点的索引 - 使用直接赋值
    (*index_map)[key] = cache->begin();
    if (cache->size() > _capacity) {
        // 淘汰最后一个元素
        index_map->erase(cache->back().m_key);  
    }
    string logmsg="PageLRUCache 缓存插入 key: "+key;
    LOG_INFO(logmsg.c_str());
}

   // 测试
#if 0
int main()
{
    KeyWordLRUCache& cache = KeyWordLRUCache::getInstance(2);
    cache.put("key1", "value1");
    cache.put("key2", "value2");
    cache.put("key3", "value3");
    std::cout<<"key1: "<<cache.get("key1")<<std::endl;
    std::cout<<"key2: "<<cache.get("key2")<<std::endl;
    std::cout<<"key3: "<<cache.get("key3")<<std::endl;
    std::cout<<"key1: "<<cache.get("key1")<<std::endl;
    std::cout<<"key2: "<<cache.get("key2")<<std::endl;
}

#endif

